package com.lingyun.ucm.web.mvc.controller;

import com.lingyun.ucm.common.exception.ServiceException;
import com.lingyun.ucm.common.util.TimeUtil;
import com.lingyun.ucm.web.mvc.service.ConfigCenterService;
import com.lingyun.ucm.web.mvc.service.impl.ConfigCenterServiceImpl;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;

/**
 * 
 * @author Terrence2013
 * 2018年1月24日 上午9:51:08
 * TODO
 */
public class Configs4SystemServlet extends HttpServlet {
    /**
     *
     */
    private static final long serialVersionUID = -8309546829340938747L;

    private ConfigCenterService configCenterService = new ConfigCenterServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String operation = req.getParameter("operation");
            if (null != operation && "download".equalsIgnoreCase(operation)) { //处理下载文件接口
                download(req, resp);
            } else {//处理其他接口
                req.setCharacterEncoding("UTF-8");
                resp.setContentType("text/html;charset=utf-8");
                //分发请求
                this.distributeOperation(req);
                req.getRequestDispatcher("/WEB-INF/pages/configs4system.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void distributeOperation(HttpServletRequest req) throws FileUploadException, IOException, ServiceException {
        String operation = req.getParameter("operation");
        String systemName;
        //初始化配置文件上传
        if (operation != null) {
            switch (operation) {
                case "upload":
                    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
                    if (isMultipart) {
                        //为该请求创建一个DiskFileItemFactory对象，通过它来解析请求
                        FileItemFactory factory = new DiskFileItemFactory();
                        ServletFileUpload upload = new ServletFileUpload(factory);
                        //将所有的表单项目都保存到List中
                        List<FileItem> items = upload.parseRequest(req);
                        Iterator<FileItem> itr = items.iterator();
                        while (itr.hasNext()) {
                            FileItem item = itr.next();
                            //检查当前项目是普通表单项目还是文件
                            if (!item.isFormField() && item.getFieldName().equals("uploadConfig")) {
                                String fileName = item.getName();
                                String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
                                configCenterService.importConfigFile(item.getInputStream(), fileType);
                            }
                        }
                    }
                    break;
                case "save":
                    systemName = req.getParameter("systemName");
                    configCenterService.saveSystem(systemName);
                    break;
                case "delete":
                    systemName = req.getParameter("systemName");
                    configCenterService.deleteSystem(systemName);
                    break;
                default:
            }
        }
        //获取系统列表
        List<String> systemNames = configCenterService.getAllSystemNames();
        req.setAttribute("systemNames", systemNames);
    }

    private void download(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String systemName = req.getParameter("systemName");
        PrintWriter out = resp.getWriter();
        //构建输出文件数据
        try {
            String jsonString = configCenterService.getDownloadString(systemName);
            //输出文件名称
            String fileName = systemName + TimeUtil.dateToStr(TimeUtil.getCurrentDate(), TimeUtil.FORMAT_MILSECOND) + ".json";
            resp.setContentType("text/plain;charset=utf-8");
            resp.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8"));
            out.write(jsonString.toCharArray());
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (null != System.out) {
                try {
                    System.out.flush();
                    System.out.close();
                } catch (Exception ex) {
                    //异常不处理
                }
            }
        }

    }
}
